package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.content.LoginUser;

import com.atguigu.lease.common.content.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * projectName: com.atguigu.lease.web.admin.interceptor
 *
 * @author: wangs
 * description:
 */

// 判断用户是否登录的拦截器
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {


    // 处理请求之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("access-token");
        if(!StringUtils.hasLength(token)){
            // 证明没有登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        // 解析token
        Claims claims = JwtUtil.parseToken(token);
        // 获取用户id
        Long userId = claims.get("userId", Long.class);
        // 获取用户名
        String username = claims.get("username", String.class);
        // 创建 LoginUser 对象
        LoginUser loginUser = new LoginUser(userId, username);
        // 将 LoginUser 放到当前线程中
        LoginUserContext.setLoginUser(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 将 LoginUser 对象从当前线程中移除
        LoginUserContext.removeLoginUser();
    }
}
